/*****************************************************************************/
//  koa2的核心中间件 app.use 
//  async function logger(ctx, next) {
//     const startDate = new Date();
//     next();
//     console.log(`method: ${ctx.method} code: ${ctx.status} time:${new Date() -startDate}ms`);
//   }
// 具体参见 koa-compose
const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const cors = require('koa-cors');
const koaBody = require('koa-bodyparser');
const jsonp = require('koa-jsonp');
const mongoose = require('mongoose');
const index = require('./routes/index');

const crosOptions = {
	'Access-Control-Allow-Origin':'*'
};

const options = {
    db: { koa2: true },
    server: { poolSize: 4 },
    replset: { rs_name: 'myReplicaSetName' }
    // user: 'root', 不需要密码直接访问本机数据库
    // pass: 'vYHDU6aTRp4p'
}
options.server.socketOptions = options.replset.socketOptions = { keepAlive: 120 }
options.server.reconnectTries = options.replset.socketOptions = { reconnectTries: 30000 }

// error handler
onerror(app)

const connection = mongoose.connect('mongodb://104.160.38.174:27017/koa2', options)

const db = mongoose.connection
db.on('error', console.error.bind(console, '鏈接失敗'))
db.once('open', function() {
    console.log('鏈接成功')
})



// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(jsonp())
app.use(logger())
app.use(cors(crosOptions))
app.use(koaBody({ multipart: true }))
app.use(require('koa-static')(__dirname + '/public'))
app.use(views(__dirname + '/views', {
    extension: 'ejs'
}))

// logger
app.use(async(ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})





// routes
app.use(index.routes(), index.allowedMethods())

module.exports = app


